import bodyParser from "body-parser";
import express from "express";
import Mock from "mockjs";
import { mockBaseUrl } from "./mock.js";

// 导入注册的mock数据
import "./index.js";

const app = express();
const port = 3001;

// 使用中间件处理请求体和CORS
app.use(bodyParser.json());

// 设置CORS头部
app.use((_, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});

// 设置Mock路由的函数
const setupMockRoutes = () => {
  console.log(24, Mock._mocked,);
  const mockApis = Mock._mocked || {};

  // 遍历每个Mock API，并生成对应的路由
  Object.keys(mockApis).forEach((key) => {
    const { rurl, rtype, template } = mockApis[key];
    // route 要以 "/"  开头！！！
    const route = rurl.replace(mockBaseUrl, "/"); // 去掉环境前缀

    // 根据请求类型（GET, POST, 等）设置路由
    app[rtype.toLowerCase()](route, (req, res) => {
      const data =
        typeof template === "function" ? template(req.body || {}) : template;
      res.json(Mock.mock(data)); // 返回模拟数据
    });
  });
};

// 设置Mock API路由
setupMockRoutes();

// 启动服务器
app.listen(port, () => {
  process.env.NODE_ENV = "mock"; // 设置环境变量
  console.log(`Mock 服务已启动，访问地址: http://localhost:${port}`);
});
